package com.yiqi.liebang.feature.mine.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiiu.filter.ClassifyBo;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.util.DateTool;
import com.yiqi.liebang.common.util.GetJsonDataUtil;
import com.yiqi.liebang.entity.bo.EducationBo;
import com.yiqi.liebang.entity.bo.JsonBean;
import com.yiqi.liebang.entity.bo.UserCardBo;
import com.yiqi.liebang.entity.bo.WorkBo;
import com.yiqi.liebang.entity.enums.CertificationStauts;
import com.yiqi.liebang.feature.home.view.ClassifyActivity;
import com.yiqi.liebang.feature.mine.contract.CertificationContract;
import com.yiqi.liebang.feature.mine.dependencies.certification.CertificationPresenterModule;
import com.yiqi.liebang.feature.mine.dependencies.certification.DaggerCertificationComponent;
import com.yiqi.liebang.feature.mine.view.adapter.WorkEditAdapter;
import com.yiqi.liebang.feature.mine.view.adapter.WorkListAdapter;
import com.yiqi.liebang.feature.setting.view.ImageActivity;
import com.yiqi.liebang.framework.DataServer;

import org.json.JSONArray;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ExpertCertificationActivity extends BaseActivity implements CertificationContract.View, RadioGroup.OnCheckedChangeListener, Toolbar.OnMenuItemClickListener {

    @Inject
    CertificationContract.Presenter mPresenter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rg_ceritifcation)
    RadioGroup mRgCeritifcation;
    @BindView(R.id.view_basic)
    LinearLayout mViewBasic;
    @BindView(R.id.view_career)
    LinearLayout mViewCareer;
    @BindView(R.id.view_education)
    LinearLayout mViewEducation;
    @BindView(R.id.iv_user_head)
    ImageView mIvUserHead;
    @BindView(R.id.edt_user_name)
    EditText mEdtUserName;

    @BindView(R.id.iv_user_card)
    ImageView mIvUserCard;
    @BindView(R.id.edt_user_industry)
    EditText mEdtUserIndustry;
    @BindView(R.id.tv_user_biaoqian)
    TextView mTvUserBiaoqian;
    @BindView(R.id.tv_user_city)
    TextView mTvUserCity;
    @BindView(R.id.tv_user_address)
    EditText mTvUserAddress;
    @BindView(R.id.tv_user_mobile)
    TextView mTvUserMobile;
    @BindView(R.id.tv_user_email)
    EditText mTvUserEmail;
    @BindView(R.id.tv_user_wechat)
    EditText mTvUserWechat;
    @BindView(R.id.tv_user_card_number)
    EditText mTvUserCardNumber;
    @BindView(R.id.iv_work_company_logo)
    ImageView mIvWorkCompanyLogo;
    @BindView(R.id.iv_work_company_name)
    TextView mTvWorkCompanyName;
    @BindView(R.id.iv_work_company_date)
    TextView mTvWorkCompanyDate;
    @BindView(R.id.tv_work_company_stauts)
    TextView mTvWorkCompanyStauts;
    @BindView(R.id.iv_work_company_stauts)
    ImageView mIvWorkCompanyStauts;
    @BindView(R.id.tv_edu_name)
    TextView mTvEduName;
    @BindView(R.id.tv_edu_date)
    TextView mTvEduDate;
    @BindView(R.id.tv_edu_stauts)
    TextView mTvEduStauts;

    @BindView(R.id.iv_edu_stauts)
    ImageView mIvEduStauts;
    @BindView(R.id.rv_work_list)
    RecyclerView mRvWorkList;
    @BindView(R.id.view_upload_work)
    LinearLayout mViewUploadWork;
    @BindView(R.id.view_upload_edu)
    LinearLayout mViewUploadEdu;
    @BindView(R.id.rv_edu_list)
    RecyclerView mRvEduList;
    @BindView(R.id.tv_work_update_time)
    TextView mTvWorkUpdateTime;
    @BindView(R.id.btn_update_ziliao)
    TextView mBtnUpdateZiliao;
    @BindView(R.id.btn_update_ziliao_edu)
    TextView mBtnUpdateZiliaoEdu;
    @BindView(R.id.tv_work_update_time_edu)
    TextView mTvWorkUpdateTimeEdu;
    @BindView(R.id.rv_show_work_imgs)
    RelativeLayout mRvShowWorkImgs;

    @BindView(R.id.rv_show_edu_imgs)
    RelativeLayout mRvShowEduImgs;
    private String mHeadUri, mCardUri;
    private int mType;
    private String mLabelsId = "";

    private List<LocalMedia> selectList;

    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private List<List<List<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    ArrayList<ClassifyBo> mLabelList = null;

    private WorkListAdapter documentAdapter;
    private String mWorkId, mEduId = "";
    //    private DocumentEduAdapter documentEduAdapter;
    private WorkBo mWorkBo = null;
    private EducationBo mEducationBo = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_expert_certification;
    }

    @Override
    protected void initInjector() {
        DaggerCertificationComponent.builder().certificationPresenterModule(new CertificationPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        switch (mType) {
            case 999:

                break;
            case 1:


                break;
            case 2:

                mPresenter.userGetWork(mWorkId);
                break;
            case 3:

                mPresenter.userGetEducation(mEduId);
                break;
        }


    }

    @Override
    protected void initView() {
        String mTitle = "";
        mType = this.getIntent().getIntExtra("type", 0);
        switch (mType) {
            case 999:
                mTitle = "认证";
                mRgCeritifcation.setVisibility(View.VISIBLE);
                mRgCeritifcation.check(R.id.rb_ceritifcation_basic);
                mViewBasic.setVisibility(View.VISIBLE);
                break;
            case 1:

                mToolbar.inflateMenu(R.menu.menu_commit);
                mTitle = "基本信息认证";
                mRgCeritifcation.setVisibility(View.GONE);
                mViewBasic.setVisibility(View.VISIBLE);
                mViewCareer.setVisibility(View.GONE);
                mViewEducation.setVisibility(View.GONE);

                break;
            case 2:
                mTitle = "职业经历认证";
                mRgCeritifcation.setVisibility(View.GONE);
                mViewBasic.setVisibility(View.GONE);
                mViewCareer.setVisibility(View.VISIBLE);
                mViewEducation.setVisibility(View.GONE);
                mWorkId = getIntent().getStringExtra("work_id");
                mPresenter.userGetWork(mWorkId);
                break;
            case 3:
                mTitle = "教育经历认证";
                mRgCeritifcation.setVisibility(View.GONE);
                mViewBasic.setVisibility(View.GONE);
                mViewCareer.setVisibility(View.GONE);
                mViewEducation.setVisibility(View.VISIBLE);
                mEduId = getIntent().getStringExtra("edu_id");
//                mPresenter.userGetEducation(mEduId);
                break;
        }

        initToolBar(mToolbar, mTitle, true, true);
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(EditOtherActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    T.showShort("Parse Failed");
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void initData() {
        mRvWorkList.setLayoutManager(new GridLayoutManager(this, 4));
        mRvEduList.setLayoutManager(new GridLayoutManager(this, 4));


        mPresenter.getUserCardData();
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void initEvent() {
        mRgCeritifcation.setOnCheckedChangeListener(this);
        mToolbar.setOnMenuItemClickListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_ceritifcation_basic:
                mViewBasic.setVisibility(View.VISIBLE);
                mViewCareer.setVisibility(View.GONE);
                mViewEducation.setVisibility(View.GONE);
                break;
            case R.id.rb_ceritifcation_career:
                mViewBasic.setVisibility(View.GONE);
                mViewCareer.setVisibility(View.VISIBLE);
                mViewEducation.setVisibility(View.GONE);

                break;
            case R.id.rb_ceritifcation_education:
                mViewBasic.setVisibility(View.GONE);
                mViewCareer.setVisibility(View.GONE);
                mViewEducation.setVisibility(View.VISIBLE);

                break;
        }
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_shenhe) {
            switch (mType) {
                case 1:
                    mPresenter.userCertification(
                            mHeadUri,
                            mEdtUserName.getText().toString(),
                            mLabelsId,
                            mEdtUserIndustry.getText().toString(),
                            mTvUserCity.getText().toString(),
                            mTvUserAddress.getText().toString(),
                            mTvUserMobile.getText().toString(),
                            mTvUserEmail.getText().toString(),
                            mTvUserWechat.getText().toString(),
                            mTvUserCardNumber.getText().toString(),
                            mCardUri
                    );
                    break;
                case 2:
//
//                    if (mWorkBo.getImg()!=null&&mWorkBo.getImg().size()>0){
//                        Intent intents = new Intent(this, CommitSuccessActivity.class);
//                        intents.putExtra("date", DateTool.getCurTimeString(DEFAULT_SDF));
//                        startActivity(intents);
//                        finish();
//
//                    }else {
//                        showMsg("请先上传工作经历证明！");
//                        return true;
//                    }
                    break;
                case 3:

//                    if (mEducationBo.getImg()!=null&&mEducationBo.getImg().size()>0){
//                        Intent intents = new Intent(this, CommitSuccessActivity.class);
//                        intents.putExtra("date", DateTool.getCurTimeString(DEFAULT_SDF));
//                        startActivity(intents);
//                        finish();
//
//                    }else {
//                        showMsg("请先上传教育经历证明！");
//                        return true;
//                    }
                    break;
            }

        }
        return false;
    }


    @OnClick({R.id.btn_edit_touxiang, R.id.btn_edit_biaoqian,
            R.id.btn_edit_diqu, R.id.btn_upload_card, R.id.btn_upload_work, R.id.btn_upload_edu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_edit_touxiang:
                initGallery(PictureConfig.SINGLE);
                break;
            case R.id.btn_edit_biaoqian:
                Intent intent = new Intent(this, ClassifyActivity.class);
                intent.putExtra("isSelect", true);
                intent.putExtra("classify", mLabelList);
                startActivityForResult(intent, 6);
                break;
            case R.id.btn_edit_diqu:
                if (isLoaded) {
                    showPickerView();
                } else {
                    T.showShort("Please waiting until the data is parsed");
                }
                break;
            case R.id.btn_upload_card:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style1)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(true)
                        .enableCrop(true)// 是否裁剪
                        .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .circleDimmedLayer(false)// 是否圆形裁剪
                        .selectionMedia(selectList)// 是否传入已选图片
                        .scaleEnabled(true)
                        .forResult(000);//结果回调onActivityResult code
                break;
            case R.id.btn_upload_work:
                Intent intentWork = new Intent(this, UploadWorkActivity.class);
                intentWork.putExtra("work_id", mWorkId);
                intentWork.putExtra("isAll", false);
                startActivity(intentWork);
                break;
            case R.id.btn_upload_edu:
                Intent intentEdu = new Intent(this, UploadEduActivity.class);
                intentEdu.putExtra("edu_id", mEduId);
                intentEdu.putExtra("isAll", false);
                startActivity(intentEdu);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.SINGLE:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        mHeadUri = selectList.get(i).getCutPath();
                    }
                    AM.image().bindToCircleObject(mHeadUri, mIvUserHead);
                    break;
                case 000:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        mCardUri = selectList.get(i).getCutPath();
                    }
                    AM.image().bind(mCardUri, mIvUserCard);
                    break;
                case 6:
                    mLabelList = data.getParcelableArrayListExtra("labels");
                    if (mLabelList != null && mLabelList.size() > 0) {
                        String lables = "";
                        mLabelsId = "";
                        for (int i = 0; i < mLabelList.size(); i++) {
                            lables += mLabelList.get(i).getClassify() + ",";
                            mLabelsId += mLabelList.get(i).getId() + ",";
                        }
                        mLabelsId = mLabelsId.substring(0, mLabelsId.length() - 1);
                        mTvUserBiaoqian.setText(lables.substring(0, lables.length() - 1));
                    } else {
                        mLabelsId = null;
                        mTvUserBiaoqian.setText("");
                    }
                    break;
            }
        }
    }

    @Override
    public void showWorkSuccess(WorkBo workBo) {
        if (workBo == null) return;
        mWorkBo = workBo;
        mTvWorkCompanyName.setText(workBo.getCompany());
        mTvWorkCompanyDate.setText(workBo.getBeginTime() + " - " + workBo.getEndTime() + " , " + workBo.getPosition());
        mTvWorkCompanyStauts.setText(CertificationStauts.getName(workBo.getStatus()));
        mIvWorkCompanyStauts.setImageResource(workBo.getStatus() == 1 ? R.drawable.icon_yanzheng : R.drawable.icon_weiyanzhneg);

        mTvWorkUpdateTime.setText(workBo.getImg() != null && workBo.getImg().size() > 0 ? DateTool.formatTime(workBo.getImg().get(0).getCreateTime()) : "");
        AM.image().bindToCircleObject(workBo.getComLogo(), mIvWorkCompanyLogo);


        if (workBo.getImg() != null && workBo.getImg().size() > 0) {
            mRvShowWorkImgs.setVisibility(View.VISIBLE);
            mViewUploadWork.setVisibility(View.GONE);
            WorkEditAdapter documentAdapter = new WorkEditAdapter();
            documentAdapter.bindToRecyclerView(mRvWorkList);
            documentAdapter.setNewData(workBo.getImg());
            documentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    Intent intentWork = new Intent(ExpertCertificationActivity.this, ImageActivity.class);
                    intentWork.putExtra("pos", position);
                    intentWork.putExtra("images", (Serializable) workBo.getImg());
                    startActivity(intentWork);
                }
            });

            mBtnUpdateZiliao.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intentWork = new Intent(ExpertCertificationActivity.this, UploadWorkActivity.class);
                    intentWork.putExtra("work_id", mWorkId);
                    intentWork.putExtra("works_imgs", (Serializable) workBo.getImg());
                    intentWork.putExtra("isAll", false);
                    startActivity(intentWork);
                }
            });

        } else {
            mViewUploadWork.setVisibility(View.VISIBLE);
            mRvShowWorkImgs.setVisibility(View.GONE);
        }

        mViewUploadEdu.setVisibility(View.GONE);

    }

    @Override
    public void showUserCardSuccess(UserCardBo s) {
        showUserInfo(s);
    }

    @Override
    public void showEducationSuccess(EducationBo workBo) {
        if (workBo == null) return;
        mEducationBo = workBo;
        mTvEduName.setText(workBo.getSchoolName());
        mTvEduDate.setText(workBo.getBeginTime() + " - " + workBo.getEndTime() + " , " + workBo.getSubjectName());
        mTvEduStauts.setText(CertificationStauts.getName(workBo.getStatus()));
        mIvEduStauts.setImageResource(workBo.getStatus() == 1 ? R.drawable.icon_yanzheng : R.drawable.icon_weiyanzhneg);


        mTvWorkUpdateTimeEdu.setText(workBo.getImg() != null && workBo.getImg().size() > 0 ? DateTool.formatTime(workBo.getImg().get(0).getCreateTime()) : "");
        ;

        mBtnUpdateZiliaoEdu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentWork = new Intent(ExpertCertificationActivity.this, UploadEduActivity.class);
                intentWork.putExtra("edu_id", mEduId);
                intentWork.putExtra("edu_imgs", (Serializable) workBo.getImg());
                intentWork.putExtra("isAll", false);
                startActivity(intentWork);
            }
        });
        if (workBo.getImg() != null && workBo.getImg().size() > 0) {
            mViewUploadEdu.setVisibility(View.GONE);
            mRvShowEduImgs.setVisibility(View.VISIBLE);
            WorkEditAdapter documentAdapter = new WorkEditAdapter();
            documentAdapter.bindToRecyclerView(mRvEduList);
            documentAdapter.setNewData(workBo.getImg());
            documentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    Intent intentWork = new Intent(ExpertCertificationActivity.this, ImageActivity.class);
                    intentWork.putExtra("pos", position);
                    intentWork.putExtra("images", (Serializable) workBo.getImg());
                    startActivity(intentWork);
                }
            });

        } else {
            mViewUploadEdu.setVisibility(View.VISIBLE);
            mRvShowEduImgs.setVisibility(View.GONE);
        }
        mViewUploadWork.setVisibility(View.GONE);
    }

    @Override
    public void showAuthWorkSuccess() {

    }

    @Override
    public void showCertificationSuccess() {
        showMsg("修改成功！");
        finish();
    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public void showWorkListSuccess(List<WorkBo> workBos) {

    }

    @Override
    public void showEduListSuccess(List<EducationBo> workBos) {

    }

    @Override
    public void showUploadAuthenticationImageSuccess() {

    }

    private void showUserInfo(UserCardBo s) {
        if (s == null) return;
        mLabelList = new ArrayList<>(s.getClassify());
        AM.image().bindToCircleObject(s.getUserHead(), mIvUserHead);

        mEdtUserName.setText(TextUtils.isEmpty(s.getUserName()) ? "" : s.getUserName());
        mEdtUserIndustry.setText(TextUtils.isEmpty(s.getUserIndustry()) ? "" : s.getUserIndustry());
        mTvUserBiaoqian.setText((s.getClassify() != null && s.getClassify().size() > 0
                ? DataServer.getClassfiyStr2(s.getClassify()) : ""));
        mTvUserCity.setText(TextUtils.isEmpty(s.getUserWorkAddress()) ? "" : s.getUserWorkAddress());
        mTvUserAddress.setText(TextUtils.isEmpty(s.getUserDetailAddress()) ? "" : s.getUserDetailAddress());
        mTvUserMobile.setText(TextUtils.isEmpty(s.getPhone()) ? "" : s.getPhone());
        mTvUserEmail.setText(TextUtils.isEmpty(s.getUserEmail()) ? "" : s.getUserEmail());
        mTvUserWechat.setText(TextUtils.isEmpty(s.getWeChatId()) ? "" : s.getWeChatId());
        mTvUserCardNumber.setText(TextUtils.isEmpty(s.getUserCardId()) ? "" : s.getUserCardId());
        AM.image().bindToCard(s.getUserCardUrlmosaic(), mIvUserCard);

//        if (!TextUtils.isEmpty(s.getUserCardUrl())) {
//            FutureTarget<File> future = Glide.with(this)
//                    .load(s.getUserCardUrl())
//                    .downloadOnly(500, 300);
//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    File cacheFile = null;
//                    try {
//                        cacheFile = future.get();
//                        mCardUri = cacheFile.getAbsolutePath();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    } catch (ExecutionException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }).start();
//        }


    }

    private void initGallery(int pos) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style1)
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isCamera(true)
                .enableCrop(true)// 是否裁剪
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .compress(true)// 是否压缩
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(true)// 是否圆形裁剪
                .selectionMedia(selectList)// 是否传入已选图片
                .scaleEnabled(true)
                .forResult(pos);//结果回调onActivityResult code
    }


    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2);
                mTvUserCity.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(R.color.div_primary)
                .setLineSpacingMultiplier(2.5f)
                .setTextColorCenter(R.color.text_primary) //设置选中项文字颜色
                .setContentTextSize(15)
                .build();


        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        List<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体


        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                List<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public List<JsonBean> parseData(String result) {//Gson 解析
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
